<template>
  <div class="registration-list-container">
    <el-page-header content="立案信息管理" @back="handleBack" class="page-header" />

    <el-card shadow="hover" class="main-card">
      <!-- 查询区域 -->
      <el-form :model="searchForm" label-width="100px" class="search-form" inline>
        <el-form-item label="立案号" prop="registrationNo">
          <el-input v-model="searchForm.registrationNo" placeholder="请输入立案号" clearable maxlength="32" />
        </el-form-item>

        <el-form-item label="报案号" prop="reportNo">
          <el-input v-model="searchForm.reportNo" placeholder="请输入报案号" clearable maxlength="32" />
        </el-form-item>

        <el-form-item label="立案状态" prop="status">
          <el-select v-model="searchForm.status" placeholder="请选择立案状态" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="已立案" value="1" />
            <el-option label="已理算" value="2" />
            <el-option label="已撤销" value="3" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表区域 -->
      <el-table v-loading="tableLoading" :data="tableData" border stripe style="width: 100%; margin-top: 10px">
        <el-table-column prop="registrationNo" label="立案号" align="center" min-width="180" />
        <el-table-column prop="reportNo" label="报案号" align="center" min-width="200" />
        <!-- <el-table-column prop="surveyNo" label="查勘单号" align="center" min-width="140" /> -->
        <el-table-column prop="operator" label="立案员工号" align="center" min-width="120" />
        <el-table-column prop="registrationAmount" label="立案金额(元)" align="center" min-width="120" />
        <el-table-column prop="liabilityDetermination" label="责任认定" align="center" min-width="140" />
        <el-table-column prop="lossType" label="损失类型" align="center" min-width="120" />
        <el-table-column prop="status" label="立案状态" align="center" min-width="100" />
        <el-table-column prop="registrationDate" label="立案日期" align="center" min-width="250" />
        <el-table-column label="操作" align="center" min-width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleView(scope.row)">
              <el-icon>
                <Eye />
              </el-icon>详情
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              <el-icon>
                <Delete />
              </el-icon>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                       :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="立案详情" :width="dialogWidth" :before-close="handleDialogClose">
      <el-descriptions column="2" border class="detail-descriptions">
        <!-- 基础信息 -->
        <el-descriptions-item label="立案号">{{ detailData.registrationNo }}</el-descriptions-item>
        <el-descriptions-item label="报案号">{{ detailData.reportNo }}</el-descriptions-item>
        <el-descriptions-item label="查勘单号">{{ detailData.surveyNo }}</el-descriptions-item>
        <el-descriptions-item label="保单号">{{ detailData.policyNo }}</el-descriptions-item>
        <el-descriptions-item label="投保人ID">{{ detailData.insuredId }}</el-descriptions-item>
        <el-descriptions-item label="立案员">{{ detailData.operator }}</el-descriptions-item>

        <!-- 时间信息 -->
        <el-descriptions-item label="立案日期">{{ detailData.registrationDate }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime }}</el-descriptions-item>

        <!-- 损失信息 -->
        <el-descriptions-item label="农户自报损失(元)">{{ formatCurrency(detailData.farmerLossEstimate)
          }}</el-descriptions-item>
        <el-descriptions-item label="立案金额(元)">{{ formatCurrency(detailData.registrationAmount) }}</el-descriptions-item>
        <el-descriptions-item label="损失类型">{{ detailData.lossType }}</el-descriptions-item>
        <el-descriptions-item label="损失范围">{{ detailData.lossScope }}</el-descriptions-item>
        <el-descriptions-item label="损失差异原因">{{ detailData.lossDiffReason }}</el-descriptions-item>

        <!-- 责任与状态 -->
        <el-descriptions-item label="责任认定">{{ detailData.liabilityDetermination }}</el-descriptions-item>
        <el-descriptions-item label="责任认定依据">{{ detailData.coverageBasis }}</el-descriptions-item>
        <el-descriptions-item label="立案状态">
          <el-select v-model="detailData.status" placeholder="请选择状态" style="width: 180px"
                     :disabled="detailData.originalStatus === '3'">
            <el-option label="已立案" value="1" />
            <el-option label="已理算" value="2" />
            <el-option label="已撤销" value="3" />
          </el-select>
        </el-descriptions-item>
        <el-descriptions-item label="撤销原因" v-if="detailData.status === '3'">
          <el-input v-model="detailData.cancelReason" placeholder="请填写撤销原因" type="textarea" :rows="2"
                    style="width: 300px" />
        </el-descriptions-item>
        <el-descriptions-item label="撤销原因" v-else>{{ detailData.cancelReason || '-' }}</el-descriptions-item>

        <!-- 状态变更操作按钮 -->
        <el-descriptions-item label="状态操作"
                              v-if="detailData.status !== detailData.originalStatus && detailData.originalStatus !== '3'">
          <el-button type="primary" size="small" @click="handleStatusChange" :loading="statusUpdateLoading">
            保存状态变更
          </el-button>
          <el-button size="small" @click="handleStatusCancel">取消</el-button>
        </el-descriptions-item>

        <!-- 备注 -->
        <!-- <el-descriptions-item label="备注" :span="2">{{ detailData.remark }}</el-descriptions-item> -->
      </el-descriptions>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog v-model="deleteVisible" title="删除确认" width="30%" :close-on-click-modal="false">
      <div class="delete-confirm-content">
        <p>您确定要删除立案号为 <span class="highlight">{{ deleteData.registrationNo }}</span> 的记录吗？</p>
        <p class="warning-text">注意：删除后数据将无法恢复，请谨慎操作！</p>
      </div>

      <template #footer>
        <el-button @click="deleteVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete" :loading="deleteLoading">
          确认删除
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted, computed} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElNotification, ElLoading} from 'element-plus'
import {Search, Eye, Delete} from '@element-plus/icons-vue'
import hxxp from '@/utils/hxxp'

// 路由实例
const router = useRouter()

// 状态/类型映射表
const statusMap = {
  '1': '已立案',
  '2': '已理算',
  '3': '已撤销'
}

const liabilityMap = {
  '1': '属于保险责任',
  '0': '不属于保险责任'
}

const lossTypeMap = {
  '1': '部分损失',
  '2': '全部损失',
  '3': '死亡损失'
}

// 状态变量
const tableLoading = ref(false)
const deleteLoading = ref(false)
const detailVisible = ref(false)
const deleteVisible = ref(false)
const statusUpdateLoading = ref(false)
const dialogWidth = computed(() => {
  return window.innerWidth < 768 ? '90%' : '800px'
})

// 搜索表单
const searchForm = reactive({
  registrationNo: '',
  reportNo: '',
  status: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 详情弹窗数据
const detailData = ref({})

// 删除弹窗数据
const deleteData = ref({})

// 格式化金额
const formatCurrency = (value) => {
  if (value === null || value === undefined) return '0.00'
  return Number(value).toFixed(2)
}

// 页面加载时获取列表数据
onMounted(() => {
  fetchRegistrationList()
})

// 获取立案列表数据
const fetchRegistrationList = async () => {
  tableLoading.value = true

  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      registrationId: searchForm.registrationNo.trim() || null,
      reportId: searchForm.reportNo.trim() || null,
      status: searchForm.status ? Number(searchForm.status) : undefined
    }

    const response = await hxxp.get('/aiClaimRegistration/list', {params})
    console.log('列表查询响应:', response)

    if (response.code === 100200) {
      // 数据映射：严格对应数据库字段到前端显示字段
      tableData.value = response.data.list.map(item => ({
        ...item,
        registrationNo: item.registrationId,
        reportNo: item.reportId,
        surveyNo: item.surveyId,
        registrationDate: item.registrationTime.replace('T', ' '),
        operator: item.registrarId || '未知',
        registrationAmount: item.surveyorLossEstimate,
        liabilityDetermination: liabilityMap[item.isCovered.toString()] || '未知',
        lossType: lossTypeMap[item.lossType.toString()] || '未知',
        status: statusMap[item.registrationStatus.toString()] || '未知'
      }))
      pagination.total = response.data.total
    } else {
      ElMessage.error(response.msg || '获取立案列表失败')
    }
  } catch (error) {
    console.error('获取立案列表失败:', error)
    ElMessage.error('获取立案列表失败，请稍后重试')
  } finally {
    tableLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchRegistrationList()
}

// 重置
const handleReset = () => {
  searchForm.registrationNo = ''
  searchForm.reportNo = ''
  searchForm.status = ''
  pagination.currentPage = 1
  pagination.pageSize = 10
  fetchRegistrationList()
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchRegistrationList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchRegistrationList()
}

// 查看详情
const handleView = async (row) => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: '加载中，请稍候...',
    target: document.querySelector('.main-card')
  })

  try {
    const response = await hxxp.get(`/aiClaimRegistration/get/${row.registrationId}`)
    console.log('详情查询响应:', response)

    if (response.code === 100200) {
      const data = response.data
      detailData.value = {
        registrationNo: data.registrationId,
        reportNo: data.reportId,
        surveyNo: data.surveyId,
        policyNo: data.policyId,
        insuredId: data.insuredId,
        registrationDate: data.registrationTime.replace('T', ' '),
        createTime: data.registrationTime.replace('T', ' '),
        updateTime: data.updateTime ? data.updateTime.replace('T', ' ') : '-',
        registrationAmount: data.surveyorLossEstimate,
        farmerLossEstimate: data.farmerLossEstimate,
        lossType: lossTypeMap[data.lossType.toString()] || '未知',
        lossScope: data.lossScope || '-',
        lossDiffReason: data.lossDiffReason || '-',
        liabilityDetermination: liabilityMap[data.isCovered.toString()] || '未知',
        coverageBasis: data.coverageBasis || '-',
        status: data.registrationStatus.toString(),
        originalStatus: data.registrationStatus.toString(), // 保存原始状态
        cancelReason: data.cancelReason || '',
        remark: data.cancelReason || data.lossDiffReason || '',
        operator: data.registrarId || '未知'
      }
      detailVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取立案详情失败')
    }
  } catch (error) {
    console.error('获取立案详情失败:', error)
    ElMessage.error('获取立案详情失败，请稍后重试')
  } finally {
    loadingInstance.close()
  }
}

// 处理状态变更
const handleStatusChange = async () => {
  if (!detailData.value.registrationNo) {
    ElMessage.warning('立案号缺失，无法更新状态')
    return
  }
  if (!detailData.value.status) {
    ElMessage.warning('请选择立案状态')
    return
  }

  // 如果状态改为已撤销，需要验证撤销原因
  if (detailData.value.status === '3') {
    if (!detailData.value.cancelReason || detailData.value.cancelReason.trim() === '') {
      ElMessage.warning('撤销立案时必须填写撤销原因')
      return
    }
  }

  statusUpdateLoading.value = true
  try {
    const params = {
      registrationId: detailData.value.registrationNo,
      registrationStatus: Number(detailData.value.status),
      cancelReason: '-'
    }

    // 如果是撤销状态，添加撤销原因参数
    if (detailData.value.status === '3') {
      params.cancelReason = detailData.value.cancelReason.trim()
    }

    const response = await hxxp.put('/aiClaimRegistration/updateStatus', null, {params})
    console.log('状态更新响应:', response)

    if (response.code === 100200) {
      ElNotification({
        title: '成功',
        message: '立案状态更新成功',
        type: 'success'
      })
      // 更新原始状态，隐藏操作按钮
      detailData.value.originalStatus = detailData.value.status
      fetchRegistrationList() // 刷新列表
    } else {
      ElMessage.error(response.msg || '更新立案状态失败')
    }
  } catch (error) {
    console.error('更新立案状态失败:', error)
    ElMessage.error('更新立案状态失败，请稍后重试')
  } finally {
    statusUpdateLoading.value = false
  }
}

// 取消状态变更
const handleStatusCancel = () => {
  // 恢复到原始状态
  detailData.value.status = detailData.value.originalStatus
  // 清空撤销原因（如果不是撤销状态）
  if (detailData.value.status !== '3') {
    detailData.value.cancelReason = ''
  }
}

// 处理删除
const handleDelete = (row) => {
  deleteData.value = {
    ...row,
    registrationId: row.registrationId
  }
  deleteVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!deleteData.value.registrationId) {
    ElMessage.warning('立案号缺失，无法删除')
    return
  }

  deleteLoading.value = true
  try {
    const response = await hxxp.delete(`/aiClaimRegistration/delete/${deleteData.value.registrationId}`)
    console.log('删除响应:', response)

    if (response.code === 100200) {
      ElMessage.success('删除成功')
      deleteVisible.value = false
      fetchRegistrationList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    console.error('删除立案记录失败:', error)
    ElMessage.error('删除失败，请稍后重试')
  } finally {
    deleteLoading.value = false
  }
}

// 关闭弹窗
const handleDialogClose = () => {
  detailVisible.value = false
}

// 返回上一页
const handleBack = () => {
  router.back()
}
</script>

<style scoped>
.registration-list-container {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.main-card {
  padding: 20px;
}

.search-form {
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.detail-descriptions {
  margin-top: 10px;
}

.delete-confirm-content {
  padding: 10px 0;
}

.highlight {
  color: #f56c6c;
  font-weight: bold;
}

.warning-text {
  color: #e6a23c;
  margin-top: 10px;
  font-size: 14px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .registration-list-container {
    padding: 10px;
  }

  .search-form {
    flex-direction: column;
    align-items: flex-start !important;
  }

  .el-form-item {
    width: 100% !important;
  }
}
</style>
